﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.Common;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.BLL.DicMgr;
using System.Text;

namespace Lenovo.CFI.Web.VP
{
    public partial class TopicIdeaReview : System.Web.UI.UserControl
    {
        TopicBl topicBl = new TopicBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int? id = UrlHelper.GetQueryStringID();
                Topic topic = null;
                if (id.HasValue)
                {
                    topic = topicBl.GetTopicByID(id.Value);
                }
                if (topic == null) ErrorHelper.RaiseNoValueError();

                ViewState["topicid"] = topic.ID;

                MessageHelper.Prepare(this.Page);


                this.HlSchedule.NavigateUrl = UrlHelper.GenerateUrl("topicschedulelist", "id", topic.ID.ToString());

                if (topic.Status != TopicStatus.Review)
                {
                    MessageHelper.RegShowJSAjax(this, "The specified topic can't edit!", this.Page);
                    this.GvList.Enabled = false;
                }

                // 可能被多个人委托
                string reviewer = UrlHelper.GetQueryString("r");
                List<Common.TopicReviewer> allReviewer = topicBl.GetReviewer(topic.ID, UserHelper.UserName);
                if (!allReviewer.Exists(r => r.Reviewer == reviewer))
                {
                    if (allReviewer.Count > 0) reviewer = allReviewer[0].Reviewer;
                }

                if (reviewer == null) ErrorHelper.RaiseNoPermError();

                ViewState["reviewer"] = reviewer;


                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "def",
                    String.Format("topicid={0};reviewer='{1}';", topic.ID, reviewer),
                    true);

                this.BindData();
            }
        }

        Dictionary<int, Idea> ideasDic = null;
        Dictionary<int, IdeaReviewDetail> reviewsDic = null;
        bool allFinished = true;
        private void BindData()
        {
            int topicID = Convert.ToInt32(ViewState["topicid"]);

            List<Idea> ideas = new IdeaBl().GetIdeaForReview(topicID);
            ideasDic = new Dictionary<int, Idea>();
            foreach (Idea idea in ideas)
                ideasDic.Add(idea.ID, idea);

            ReviewBl reviewBl = new ReviewBl();

            List<IdeaReviewDetail> reviews = reviewBl.GetReviewDetail(topicID, (string)ViewState["reviewer"]);
            reviewsDic = new Dictionary<int, IdeaReviewDetail>();
            foreach (IdeaReviewDetail review in reviews)
                reviewsDic.Add(review.ReviewID, review);

            if(reviews.Count==0)
                allFinished = false;
            else
                allFinished = !reviews.Exists(r => !r.Finished);

            GvList.DataSource = new ReviewBl().GetReview(topicID);
            GvList.DataBind();

            if (allFinished) this.BtnFinish.Enabled = false;
        }

        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);


                IdeaReview review = (IdeaReview)e.Row.DataItem;
                Idea idea = ideasDic[review.IdeaID];
                IdeaReviewDetail reviewDetail = null;
                if (reviewsDic.ContainsKey(review.ID)) reviewDetail = reviewsDic[review.ID];

                ((Literal)e.Row.FindControl("LtrStartTime")).Text = review.ReviewTime.Value.ToString("HH:mm");
                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(idea.Type).Title;
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;

                if (review.ReviewStatus == IdeaReviewStatus.Waiting)
                    e.Row.CssClass += " waiting";
                else if (review.ReviewStatus == IdeaReviewStatus.OnGoing)
                    e.Row.CssClass += " ongoing";
                else if (review.ReviewStatus == IdeaReviewStatus.Finished)
                    e.Row.CssClass += " finished";
                else if (review.ReviewStatus == IdeaReviewStatus.Summary)
                    e.Row.CssClass += " finished";

                bool bindSaveEvent = false;
                TextBox txtCv = (TextBox)e.Row.FindControl("TxtCv");
                TextBox txtBv = (TextBox)e.Row.FindControl("TxtBv");
                TextBox txtTv = (TextBox)e.Row.FindControl("TxtTv");
                DropDownList ddlType = (DropDownList)e.Row.FindControl("DdlType");
                TextBox txtComment = (TextBox)e.Row.FindControl("TxtComment");
                DropDownList ddlSuggestion = (DropDownList)e.Row.FindControl("DdlSuggestion");
                DropDownList ddlIp = (DropDownList)e.Row.FindControl("DdlIP");
                TextBox txtIPComment = (TextBox)e.Row.FindControl("TxtIPComment");
                if (reviewDetail != null)
                {
                    txtCv.Text = reviewDetail.Cv.HasValue ? reviewDetail.Cv.Value.ToString() : "";
                    txtBv.Text = reviewDetail.Bv.HasValue ? reviewDetail.Bv.Value.ToString() : "";
                    txtTv.Text = reviewDetail.Tv.HasValue ? reviewDetail.Tv.Value.ToString() : "";
                    BindHelper.BindIdeaType(ddlType, "Select...", "", reviewDetail.Type, false);
                    txtComment.Text = reviewDetail.TypeComment;
                    BindHelper.BindNextAction(ddlSuggestion, "Select...", "", reviewDetail.Suggestion, false);
                    ddlIp.SelectedIndex = (reviewDetail.Ip.HasValue ? (reviewDetail.Ip.Value ? 1 : 2) : 0);
                    txtIPComment.Text = reviewDetail.IpComment;
                }
                else
                {
                    if (!allFinished)
                    {
                        BindHelper.BindIdeaType(ddlType, "Select...", "", null, false);
                        BindHelper.BindNextAction(ddlSuggestion, "Select...", "", null, false);
                    }
                }

                if (allFinished)
                {
                    txtCv.ReadOnly = true;
                    txtBv.ReadOnly = true;
                    txtTv.ReadOnly = true;
                    ddlType.Enabled = false;
                    txtComment.ReadOnly = true;
                    ddlSuggestion.Enabled = false;
                    ddlIp.Enabled = false;
                    txtIPComment.ReadOnly = true;

                    bindSaveEvent = false;
                }
                else
                {
                    bindSaveEvent = true;
                }


                if (bindSaveEvent)
                {
                    txtCv.Attributes["onchange"] = String.Format("javascript:savecv({0}, this);", review.ID);
                    txtBv.Attributes["onchange"] = String.Format("javascript:savebv({0}, this);", review.ID);
                    txtTv.Attributes["onchange"] = String.Format("javascript:savetv({0}, this);", review.ID);

                    ddlType.Attributes["onchange"] = String.Format("javascript:savetype({0}, this);", review.ID);
                    txtComment.Attributes["onchange"] = String.Format("javascript:savecomment({0}, this);", review.ID);
                    ddlSuggestion.Attributes["onchange"] = String.Format("javascript:savesuggestion({0}, this);", review.ID);
                    ddlIp.Attributes["onchange"] = String.Format("javascript:saveip({0}, this);", review.ID);
                    txtIPComment.Attributes["onchange"] = String.Format("javascript:saveipcomment({0}, this);", review.ID);
                }
            }
        }

        protected void BtnRefresh_Click(object sender, EventArgs e)
        {
            this.BindData();
        }

        protected void BtnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().Finish((int)ViewState["topicid"], (string)ViewState["reviewer"]);

                MessageHelper.Show("Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.Show(ex.Message, this.Page);
            }

            this.BindData();
        }
    }
}